<template>
  <div class="invoice-detail">
    <a-skeleton v-if="loading" :loading="loading" active></a-skeleton>

    <template v-else>
      <a-page-header class="page-header" title="发票详情" @back="goBack">
        <template #extra>
          <a-space>
            <a-button type="primary" @click="goToEdit">
              <template #icon>
                <EditOutlined/>
              </template>
              编辑
            </a-button>
            <a-button @click="printInvoice">
              <template #icon>
                <PrinterOutlined/>
              </template>
              打印
            </a-button>
          </a-space>
        </template>
      </a-page-header>

      <a-card class="invoice-card">
        <a-typography-title :level="4">发票基本信息</a-typography-title>
        <a-row :gutter="16">
          <a-col :span="8">
            <div class="detail-item">
              <div class="detail-label">发票编号：</div>
              <div class="detail-value">{{ invoice.invoiceNumber }}</div>
            </div>
          </a-col>
          <a-col :span="8">
            <div class="detail-item">
              <div class="detail-label">分类：</div>
              <div class="detail-value">{{ getCategoryText(invoice.category) }}</div>
            </div>
          </a-col>
          <a-col :span="8">
            <div class="detail-item">
              <div class="detail-label">开票日期：</div>
              <div class="detail-value">{{ invoice.issueDate }}</div>
            </div>
          </a-col>
          <a-col :span="8">
            <div class="detail-item">
              <div class="detail-label">价税合计：</div>
              <div class="detail-value highlight-text">¥{{ formatAmount(totalAmountWithTax) }}</div>
            </div>
          </a-col>
          <a-col :span="8">
            <div class="detail-item">
              <div class="detail-label">开票人：</div>
              <div class="detail-value">{{ invoice.issuer || '无' }}</div>
            </div>
          </a-col>
          <a-col :span="8">
            <div class="detail-item">
              <div class="detail-label">创建时间：</div>
              <div class="detail-value">{{ formatDateTime(invoice.createTime) }}</div>
            </div>
          </a-col>
        </a-row>

        <a-divider/>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-typography-title :level="5">购买方信息</a-typography-title>
            <div class="info-item">
              <div class="info-content">
                <a-descriptions :column="1" bordered size="small">
                  <a-descriptions-item label="名称">{{ purchaserInfo?.name || '无' }}</a-descriptions-item>
                  <a-descriptions-item v-if="purchaserInfo?.taxNumber" label="纳税人识别号">{{
                      purchaserInfo.taxNumber
                    }}
                  </a-descriptions-item>
                  <a-descriptions-item v-if="purchaserInfo?.address" label="地址">{{
                      purchaserInfo.address
                    }}
                  </a-descriptions-item>
                  <a-descriptions-item v-if="purchaserInfo?.phone" label="电话">{{
                      purchaserInfo.phone
                    }}
                  </a-descriptions-item>
                  <a-descriptions-item v-if="purchaserInfo?.bank" label="开户行">{{
                      purchaserInfo.bank
                    }}
                  </a-descriptions-item>
                  <a-descriptions-item v-if="purchaserInfo?.bankAccount" label="账号">{{
                      purchaserInfo.bankAccount
                    }}
                  </a-descriptions-item>
                </a-descriptions>
              </div>
            </div>
          </a-col>

          <a-col :span="12">
            <a-typography-title :level="5">销售方信息</a-typography-title>
            <div class="info-item">
              <div class="info-content">
                <a-descriptions :column="1" bordered size="small">
                  <a-descriptions-item label="名称">{{ sellerInfo?.name || '无' }}</a-descriptions-item>
                  <a-descriptions-item v-if="sellerInfo?.taxNumber" label="纳税人识别号">{{
                      sellerInfo.taxNumber
                    }}
                  </a-descriptions-item>
                  <a-descriptions-item v-if="sellerInfo?.address" label="地址">{{
                      sellerInfo.address
                    }}
                  </a-descriptions-item>
                  <a-descriptions-item v-if="sellerInfo?.phone" label="电话">{{
                      sellerInfo.phone
                    }}
                  </a-descriptions-item>
                  <a-descriptions-item v-if="sellerInfo?.bank" label="开户行">{{
                      sellerInfo.bank
                    }}
                  </a-descriptions-item>
                  <a-descriptions-item v-if="sellerInfo?.bankAccount" label="账号">{{
                      sellerInfo.bankAccount
                    }}
                  </a-descriptions-item>
                </a-descriptions>
              </div>
            </div>
          </a-col>
        </a-row>

        <a-divider/>

        <a-typography-title :level="4">发票明细信息</a-typography-title>

        <!-- 明细统计卡片 -->
        <a-row :gutter="16" style="margin-bottom: 16px;">
          <a-col :span="8">
            <a-card class="stat-card">
              <template #title>
                <span class="stat-title">明细数量</span>
              </template>
              <div class="stat-value">{{ invoice.details?.length || 0 }} 项</div>
            </a-card>
          </a-col>
          <a-col :span="8">
            <a-card class="stat-card">
              <template #title>
                <span class="stat-title">合计金额</span>
              </template>
              <div class="stat-value">¥{{ formatAmount(totalAmount) }}</div>
            </a-card>
          </a-col>
          <a-col :span="8">
            <a-card class="stat-card">
              <template #title>
                <span class="stat-title">合计税额</span>
              </template>
              <div class="stat-value">¥{{ formatAmount(totalTax) }}</div>
            </a-card>
          </a-col>
        </a-row>

        <!-- 明细表格和折叠控制 -->
        <div class="detail-table-container">
          <div class="detail-header">
            <a-typography-title :level="5">发票明细列表</a-typography-title>
            <a-button class="expand-btn" type="link" @click="expandDetails = !expandDetails">
              {{ expandDetails ? '收起' : '展开' }}
              <template #icon>
                <down-outlined v-if="!expandDetails"/>
                <up-outlined v-else/>
              </template>
            </a-button>
          </div>

          <div v-show="expandDetails">
            <template v-if="invoice.details && invoice.details.length > 0">
              <a-table :columns="columns" :dataSource="invoice.details" :pagination="{
                pageSize: 5,
                showTotal: total => `共 ${total} 条明细`,
                showSizeChanger: true,
                pageSizeOptions: ['5', '10', '20', '50'],
                showQuickJumper: true
              }" bordered class="detail-table">
                <template #bodyCell="{ column, record }">
                  <template v-if="column.dataIndex === 'taxRate'">
                    {{ record.taxRate }}%
                  </template>
                  <template
                      v-else-if="column.dataIndex === 'amount' || column.dataIndex === 'taxAmount' || column.dataIndex === 'unitPrice'">
                    {{ formatAmount(record[column.dataIndex]) }}
                  </template>
                </template>
                <template #footer>
                  <div class="table-footer">
                    <div class="total-row">
                      <span>合计金额：</span>
                      <span class="total-amount">¥{{ formatAmount(totalAmount) }}</span>
                    </div>
                    <div class="total-row">
                      <span>合计税额：</span>
                      <span class="total-amount">¥{{ formatAmount(totalTax) }}</span>
                    </div>
                    <div class="total-row">
                      <span>价税合计：</span>
                      <span class="total-amount highlight">¥{{ formatAmount(totalAmountWithTax) }}</span>
                    </div>
                  </div>
                </template>
              </a-table>
            </template>
            <template v-else>
              <a-empty class="empty-details" description="暂无发票明细数据"/>
            </template>
          </div>
        </div>

        <a-divider/>

        <!-- 价税合计汇总卡片 -->
        <div class="summary-container">
          <a-row :gutter="16">
            <a-col :span="24">
              <a-card class="summary-card">
                <div class="summary-content">
                  <div class="summary-label">价税合计（人民币大写）：</div>
                  <div class="summary-value">{{ convertCurrency(totalAmountWithTax) }}</div>
                </div>
                <div class="summary-content">
                  <div class="summary-label">价税合计（小写）：</div>
                  <div class="summary-value highlight-money">¥{{ formatAmount(totalAmountWithTax) }}</div>
                </div>
              </a-card>
            </a-col>
          </a-row>
        </div>

        <a-divider/>

        <div class="detail-item">
          <div class="detail-label">备注：</div>
          <div class="detail-value">{{ invoice.remarks || '无' }}</div>
        </div>

        <!-- 关联订单部分 -->
        <a-divider/>
        <a-typography-title :level="4">关联订单</a-typography-title>
        <div v-if="relatedOrders.length > 0">
          <a-table :columns="orderColumns" :dataSource="relatedOrders" :pagination="false" bordered>
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'action'">
                <a-button type="link" @click="viewOrder(record.id)">查看</a-button>
                <a-popconfirm
                    title="确定要删除此关联订单吗？"
                    @confirm="deleteOrderRelation(record.id)"
                >
                  <a-button danger type="link">删除关联</a-button>
                </a-popconfirm>
              </template>
              <template v-else-if="column.dataIndex === 'totalAmount'">
                {{ formatAmount(record.totalAmount) }}
              </template>
            </template>
          </a-table>
        </div>
        <a-empty v-else description="暂无关联订单"/>

        <template v-if="invoice.filePath">
          <a-divider/>
          <a-typography-title :level="4">
            发票原件
            <a-tag v-if="isImage" color="blue">图片</a-tag>
            <a-tag v-else-if="isPdf" color="red">PDF</a-tag>
            <a-tag v-else color="orange">文件</a-tag>
          </a-typography-title>

          <div class="file-preview">
            <div v-if="isImage" class="image-preview">
              <!-- 使用a-image组件替换普通img标签，支持点击预览大图 -->
              <a-image :preview="{
                visible: previewVisible,
                onVisibleChange: (visible) => previewVisible = visible,
                src: fileUrl
              }" :src="fileUrl" alt="发票图片"/>

              <!-- 图片工具栏 -->
              <div class="image-toolbar">
                <a-button title="查看原图" type="primary" @click="showImagePreview">
                  <EyeOutlined/>
                  查看原图
                </a-button>
                <a-button title="下载原图" @click="downloadImage">
                  <DownloadOutlined/>
                  下载
                </a-button>
                <a-button title="在新窗口打开" @click="openInNewTab">
                  <FullscreenOutlined/>
                  新窗口打开
                </a-button>
              </div>
            </div>

            <div v-else-if="isPdf" class="pdf-preview">
              <a :href="fileUrl" target="_blank">
                <FilePdfOutlined style="font-size: 48px; color: #ff4d4f;"/>
                <div>查看PDF文件</div>
              </a>
              <!-- PDF工具栏 -->
              <div class="pdf-toolbar">
                <a-button :href="fileUrl" target="_blank" type="primary">
                  <EyeOutlined/>
                  查看PDF
                </a-button>
                <a-button :href="fileUrl" download>
                  <DownloadOutlined/>
                  下载PDF
                </a-button>
              </div>
            </div>

            <div v-else class="other-file">
              <a :href="fileUrl" target="_blank">
                <FileOutlined style="font-size: 48px;"/>
                <div>下载文件</div>
              </a>
              <!-- 文件工具栏 -->
              <div class="file-toolbar">
                <a-button :href="fileUrl" download type="primary">
                  <DownloadOutlined/>
                  下载文件
                </a-button>
              </div>
            </div>
          </div>
        </template>
      </a-card>
    </template>
  </div>
</template>

<script lang="ts">
/**
 * 发票详情组件
 *
 * 功能：
 * 1. 展示发票的详细信息，包括基本信息、购买方和销售方信息、发票明细等
 * 2. 提供编辑和打印功能
 * 3. 支持查看发票原件（图片或PDF文件）
 * 4. 显示发票金额汇总信息
 */
import {computed, defineComponent, onMounted, ref, watch} from 'vue';
import {useRoute, useRouter} from 'vue-router';
import {ElMessage} from 'element-plus';
import {
  DownloadOutlined,
  DownOutlined,
  EditOutlined,
  EyeOutlined,
  FileOutlined,
  FilePdfOutlined,
  FullscreenOutlined,
  PrinterOutlined,
  RotateRightOutlined,
  UpOutlined,
  ZoomInOutlined,
  ZoomOutOutlined
} from '@ant-design/icons-vue';
import {
  deleteInvoiceOrderRelation,
  getInvoiceById,
  getInvoiceFileUrl,
  getInvoiceRelatedOrders
} from '../../api/invoice';

export default defineComponent({
  name: 'InvoiceDetail',
  components: {
    EditOutlined,
    PrinterOutlined,
    FilePdfOutlined,
    FileOutlined,
    DownOutlined,
    UpOutlined,
    EyeOutlined,
    FullscreenOutlined,
    DownloadOutlined,
    RotateRightOutlined,
    ZoomInOutlined,
    ZoomOutOutlined
  },
  setup() {
    /**
     * 路由和导航相关
     */
    const router = useRouter();
    const route = useRoute();

    /**
     * 页面状态
     */
    const loading = ref(true);      // 加载状态
    const invoice = ref<any>({});   // 发票数据
    const expandDetails = ref(true);  // 默认展开明细表格
    const previewVisible = ref(false);  // 图片预览状态
    const relatedOrders = ref<any[]>([]);

    /**
     * 发票明细表格列定义
     * 配置表格的各列属性
     */
    const columns = [
      {
        title: '序号',
        dataIndex: 'index',
        key: 'index',
        width: 60,
        align: 'center',
        customRender: ({index}) => index + 1
      },
      {
        title: '项目名称',
        dataIndex: 'itemName',
        key: 'itemName',
        width: 180,
      },
      {
        title: '规格型号',
        dataIndex: 'specificationModel',
        key: 'specificationModel',
        width: 150,
        customRender: ({record}) => {
          // 优先使用specificationModel字段，如果没有则尝试使用specification字段
          return record.specificationModel || record.specification || '-';
        }
      },
      {
        title: '单位',
        dataIndex: 'unit',
        key: 'unit',
        width: 80,
        align: 'center',
      },
      {
        title: '数量',
        dataIndex: 'quantity',
        key: 'quantity',
        width: 100,
        align: 'right',
      },
      {
        title: '单价(元)',
        dataIndex: 'unitPrice',
        key: 'unitPrice',
        width: 120,
        align: 'right',
        customRender: ({text, record}) => {
          // 优先使用unitPrice字段，如果没有则尝试使用price字段
          const price = record.unitPrice || record.price || 0;
          return formatAmount(price);
        }
      },
      {
        title: '金额(元)',
        dataIndex: 'amount',
        key: 'amount',
        width: 120,
        align: 'right',
      },
      {
        title: '税率(%)',
        dataIndex: 'taxRate',
        key: 'taxRate',
        width: 90,
        align: 'right',
      },
      {
        title: '税额(元)',
        dataIndex: 'taxAmount',
        key: 'taxAmount',
        width: 120,
        align: 'right',
      },
    ];

    // 订单表格列定义
    const orderColumns = [
      {
        title: '订单编号',
        dataIndex: 'orderNumber',
        key: 'orderNumber',
      },
      {
        title: '供应商',
        dataIndex: 'supplierName',
        key: 'supplierName',
      },
      {
        title: '订单金额',
        dataIndex: 'totalAmount',
        key: 'totalAmount',
      },
      {
        title: '订单状态',
        dataIndex: 'status',
        key: 'status',
      },
      {
        title: '操作',
        key: 'action',
        width: 200,
      }
    ];

    /**
     * 判断发票附件是否为图片
     * 通过文件扩展名判断
     */
    const isImage = computed(() => {
      if (!invoice.value.filePath) return false;
      const fileExt = invoice.value.filePath.split('.').pop()?.toLowerCase();
      return ['jpg', 'jpeg', 'png', 'gif', 'bmp'].includes(fileExt);
    });

    /**
     * 判断发票附件是否为PDF
     * 通过文件扩展名判断
     */
    const isPdf = computed(() => {
      if (!invoice.value.filePath) return false;
      const fileExt = invoice.value.filePath.split('.').pop()?.toLowerCase();
      return fileExt === 'pdf';
    });

    /**
     * 获取文件URL
     * 直接返回发票原始URL
     */
    const fileUrl = computed(() => {
      if (!invoice.value.filePath) return '';

      // 直接使用原始URL
      if (invoice.value.filePath.startsWith('https://')) {
        return invoice.value.filePath;
      }

      // 对于非https开头的路径，使用API工具函数处理
      return getInvoiceFileUrl(invoice.value.filePath);
    });

    /**
     * 计算属性：解析购买方和销售方信息
     */
    const purchaserInfo = computed(() => {
      if (!invoice.value || !invoice.value.purchaserInfo) return {};

      try {
        // 如果是字符串，尝试进行JSON解析
        if (typeof invoice.value.purchaserInfo === 'string') {
          // 检查是否是JSON格式的字符串
          if (invoice.value.purchaserInfo.startsWith('{') && invoice.value.purchaserInfo.endsWith('}')) {
            return JSON.parse(invoice.value.purchaserInfo);
          } else {
            // 非JSON格式的字符串，创建一个只包含名称的对象
            return {name: invoice.value.purchaserInfo};
          }
        }

        // 如果已经是对象，直接返回
        if (typeof invoice.value.purchaserInfo === 'object') {
          return invoice.value.purchaserInfo;
        }

        // 其他情况，返回空对象
        return {};
      } catch (error) {
        console.error('解析购买方信息失败:', error);
        // 解析失败时，创建一个只包含原始值作为名称的对象
        return {name: invoice.value.purchaserInfo};
      }
    });

    const sellerInfo = computed(() => {
      if (!invoice.value || !invoice.value.sellerInfo) return {};

      try {
        // 如果是字符串，尝试进行JSON解析
        if (typeof invoice.value.sellerInfo === 'string') {
          // 检查是否是JSON格式的字符串
          if (invoice.value.sellerInfo.startsWith('{') && invoice.value.sellerInfo.endsWith('}')) {
            return JSON.parse(invoice.value.sellerInfo);
          } else {
            // 非JSON格式的字符串，创建一个只包含名称的对象
            return {name: invoice.value.sellerInfo};
          }
        }

        // 如果已经是对象，直接返回
        if (typeof invoice.value.sellerInfo === 'object') {
          return invoice.value.sellerInfo;
        }

        // 其他情况，返回空对象
        return {};
      } catch (error) {
        console.error('解析销售方信息失败:', error);
        // 解析失败时，创建一个只包含原始值作为名称的对象
        return {name: invoice.value.sellerInfo};
      }
    });

    /**
     * 计算属性：发票金额汇总
     */
    const totalAmount = computed(() => {
      if (!invoice.value.details || invoice.value.details.length === 0) return 0;
      return invoice.value.details.reduce((sum: number, item: any) => {
        return sum + (Number(item.amount) || 0);
      }, 0);
    });

    const totalTax = computed(() => {
      if (!invoice.value.details || invoice.value.details.length === 0) return 0;
      return invoice.value.details.reduce((sum: number, item: any) => {
        return sum + (Number(item.taxAmount) || 0);
      }, 0);
    });

    const totalAmountWithTax = computed(() => {
      return totalAmount.value + totalTax.value;
    });

    /**
     * 获取发票关联的订单
     */
    const fetchRelatedOrders = async (invoiceId: string) => {
      try {
        const response = await getInvoiceRelatedOrders(invoiceId);
        if (response && response.data) {
          relatedOrders.value = response.data;
        } else {
          relatedOrders.value = [];
        }
      } catch (error) {
        console.error('获取关联订单失败:', error);
        relatedOrders.value = [];
      }
    };

    /**
     * 获取发票数据
     * 根据路由ID参数从服务器获取发票详细信息
     */
    const fetchInvoice = async (id: string | string[]) => {
      loading.value = true;
      try {
        const response = await getInvoiceById(id as string);

        // 处理API响应
        if (response && response.data) {
          // API返回了Result包装的数据
          if (!response.success) {
            ElMessage.error(response.message || '获取发票详情失败');
            return;
          }

          // 设置发票数据
          invoice.value = normalizeInvoiceData(response.data);

          // 获取关联订单
          fetchRelatedOrders(id as string);
        } else if (response) {
          // API直接返回了发票对象
          invoice.value = normalizeInvoiceData(response);

          // 获取关联订单
          fetchRelatedOrders(id as string);
        } else {
          ElMessage.error('获取发票详情失败：API返回空数据');
        }
      } catch (error) {
        console.error('获取发票详情失败:', error);
        ElMessage.error('获取发票详情失败，请稍后重试');
      } finally {
        loading.value = false;
      }
    };

    /**
     * 规范化发票数据
     * 确保关键数据字段存在且格式正确
     */
    const normalizeInvoiceData = (data: any) => {
      if (!data) return {};

      // 确保details字段为数组
      if (!data.details) {
        data.details = [];
      }

      // 处理details字段，确保规格型号字段正确映射
      if (data.details && Array.isArray(data.details)) {
        data.details = data.details.map(detail => {
          // 确保规格型号字段存在
          if (detail.specification && !detail.specificationModel) {
            detail.specificationModel = detail.specification;
          }

          return detail;
        });
      }

      // 确保purchaserInfo和sellerInfo格式正确
      if (data.purchaserInfo) {
        // 尝试将purchaserInfo标准化为对象格式
        if (typeof data.purchaserInfo === 'string' && !data.purchaserInfo.startsWith('{')) {
          try {
            // 如果包含分隔符，尝试解析为结构化数据
            if (data.purchaserInfo.includes('：') || data.purchaserInfo.includes(':')) {
              const lines = data.purchaserInfo.split(/[,，\n]/);
              const info: any = {name: lines[0] || data.purchaserInfo};

              for (const line of lines) {
                if (line.includes('名称：') || line.includes('名称:')) {
                  info.name = line.split(/[：:]/)[1]?.trim();
                } else if (line.includes('税号：') || line.includes('税号:')) {
                  info.taxNumber = line.split(/[：:]/)[1]?.trim();
                } else if (line.includes('地址：') || line.includes('地址:')) {
                  info.address = line.split(/[：:]/)[1]?.trim();
                } else if (line.includes('电话：') || line.includes('电话:')) {
                  info.phone = line.split(/[：:]/)[1]?.trim();
                } else if (line.includes('开户行：') || line.includes('开户行:')) {
                  info.bank = line.split(/[：:]/)[1]?.trim();
                } else if (line.includes('账号：') || line.includes('账号:')) {
                  info.bankAccount = line.split(/[：:]/)[1]?.trim();
                }
              }

              data.purchaserInfo = JSON.stringify(info);
            } else {
              // 简单字符串，包装为JSON格式
              data.purchaserInfo = JSON.stringify({name: data.purchaserInfo});
            }
          } catch (e) {
            console.error('规范化购买方信息失败:', e);
          }
        }
      }

      // 对销售方信息进行类似处理
      if (data.sellerInfo) {
        if (typeof data.sellerInfo === 'string' && !data.sellerInfo.startsWith('{')) {
          try {
            // 如果包含分隔符，尝试解析为结构化数据
            if (data.sellerInfo.includes('：') || data.sellerInfo.includes(':')) {
              const lines = data.sellerInfo.split(/[,，\n]/);
              const info: any = {name: lines[0] || data.sellerInfo};

              for (const line of lines) {
                if (line.includes('名称：') || line.includes('名称:')) {
                  info.name = line.split(/[：:]/)[1]?.trim();
                } else if (line.includes('税号：') || line.includes('税号:')) {
                  info.taxNumber = line.split(/[：:]/)[1]?.trim();
                } else if (line.includes('地址：') || line.includes('地址:')) {
                  info.address = line.split(/[：:]/)[1]?.trim();
                } else if (line.includes('电话：') || line.includes('电话:')) {
                  info.phone = line.split(/[：:]/)[1]?.trim();
                } else if (line.includes('开户行：') || line.includes('开户行:')) {
                  info.bank = line.split(/[：:]/)[1]?.trim();
                } else if (line.includes('账号：') || line.includes('账号:')) {
                  info.bankAccount = line.split(/[：:]/)[1]?.trim();
                }
              }

              data.sellerInfo = JSON.stringify(info);
            } else {
              // 简单字符串，包装为JSON格式
              data.sellerInfo = JSON.stringify({name: data.sellerInfo});
            }
          } catch (e) {
            console.error('规范化销售方信息失败:', e);
          }
        }
      }

      return data;
    };

    /**
     * 返回发票列表页
     */
    const goBack = () => {
      router.push({name: 'InvoiceList'});
    };

    /**
     * 跳转到发票编辑页面
     * 将当前发票ID传递给编辑页面
     */
    const goToEdit = () => {
      router.push({
        name: 'InvoiceEdit',
        params: {id: route.params.id}
      });
    };

    /**
     * 打印发票
     * 调用浏览器打印功能
     */
    const printInvoice = () => {
      // 设置打印样式
      const styleElement = document.createElement('style');
      styleElement.id = 'print-style';
      styleElement.innerHTML = `
        @media print {
          body * {
            visibility: hidden;
          }
          .invoice-card, .invoice-card * {
            visibility: visible;
          }
          .page-header, .ant-btn, .ant-pagination {
            display: none !important;
          }
          .invoice-card {
            position: absolute;
            left: 0;
            top: 0;
            width: 100%;
            padding: 20px;
            margin: 0;
          }
        }
      `;
      document.head.appendChild(styleElement);

      // 打印
      window.print();

      // 移除打印样式
      setTimeout(() => {
        const element = document.getElementById('print-style');
        if (element) element.remove();
      }, 1000);
    };

    /**
     * 获取发票类型的显示文本
     * 将代码值转换为用户友好的显示文本
     *
     * @param category 发票类型代码
     * @returns 发票类型显示文本
     */
    const getCategoryText = (category: string) => {
      // 如果category已经是中文描述，直接返回
      if (typeof category === 'string' && (
          category === '增值税专用发票' ||
          category === '增值税普通发票' ||
          category === '增值税电子发票' ||
          category === '收据' ||
          category === '其他'
      )) {
        return category;
      }

      // 兼容旧数据，将代码转换为文本
      const categories = {
        'VAT_SPECIAL': '增值税专用发票',
        'VAT_ORDINARY': '增值税普通发票',
        'VAT_ELECTRONIC': '增值税电子发票',
        'RECEIPT': '收据',
        'OTHER': '其他'
      };
      return categories[category as keyof typeof categories] || category;
    };

    /**
     * 格式化金额显示
     * 保留两位小数并添加千分位分隔符
     *
     * @param amount 要格式化的金额
     * @returns 格式化后的金额字符串
     */
    const formatAmount = (amount: number) => {
      if (!amount && amount !== 0) return '0.00';
      return amount.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
    };

    /**
     * 格式化日期时间显示
     * 将时间戳转换为可读的日期时间格式
     *
     * @param timestamp 时间戳
     * @returns 格式化后的日期时间字符串
     */
    const formatDateTime = (timestamp: number) => {
      if (!timestamp) return '无';
      const date = new Date(timestamp);
      return date.toLocaleString();
    };

    /**
     * 将数字金额转换为中文大写
     *
     * @param money 金额数字
     * @returns 中文大写金额
     */
    const convertCurrency = (money: number) => {
      if (!money && money !== 0) return '零元整';

      // 转为字符串，并确保有两位小数
      const moneyStr = money.toFixed(2);
      // 拆分整数和小数部分
      const parts = moneyStr.split('.');
      const intPart = parts[0];
      const decPart = parts[1];

      // 数字对应的汉字
      const cnNums = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
      // 整数部分单位
      const intUnits = ['', '拾', '佰', '仟', '万', '拾', '佰', '仟', '亿', '拾', '佰', '仟', '万'];
      // 小数部分单位
      const decUnits = ['角', '分'];

      // 转换整数部分
      let intCn = '';
      let zero = false; // 前一位是否为零
      for (let i = 0; i < intPart.length; i++) {
        const n = parseInt(intPart[i]);
        const pos = intPart.length - i - 1; // 单位位置

        // 万、亿位前需要加单位
        if (pos % 4 === 0 && i > 0) {
          // 判断万、亿之前是否有有效数字
          if (intCn !== '') {
            intCn += intUnits[pos];
          }
          zero = true; // 重置零标志
        }

        if (n === 0) {
          if (!zero) {
            zero = true;
            intCn += cnNums[n];
          }
        } else {
          zero = false;
          intCn += cnNums[n] + intUnits[pos % 4];
        }
      }
      intCn += '元';

      // 转换小数部分
      let decCn = '';
      if (parseInt(decPart) === 0) {
        decCn = '整';
      } else {
        for (let i = 0; i < decPart.length; i++) {
          const n = parseInt(decPart[i]);
          if (n !== 0) {
            decCn += cnNums[n] + decUnits[i];
          } else if (i === 0 && parseInt(decPart[1]) !== 0) {
            decCn += cnNums[n]; // 角位为0，但分位不为0时，需要加上"零"
          }
        }
      }

      return intCn + decCn;
    };

    /**
     * 组件挂载时获取发票数据
     */
    onMounted(() => {
      fetchInvoice(route.params.id);
    });

    // 监听路由参数变化
    watch(
        () => route.params.id,
        (newId) => {
          if (newId) {
            fetchInvoice(newId);
          }
        }
    );

    /**
     * 显示图片预览
     */
    const showImagePreview = () => {
      previewVisible.value = true;
    };

    /**
     * 下载图片
     */
    const downloadImage = () => {
      if (!fileUrl.value) return;

      // 创建一个临时的a标签触发下载
      const link = document.createElement('a');
      link.href = fileUrl.value;
      // 设置下载文件名 - 使用原始文件名或默认名称
      const fileName = invoice.value.filePath.split('/').pop() || 'invoice.jpg';
      link.download = fileName;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    };

    /**
     * 在新窗口打开图片
     */
    const openInNewTab = () => {
      if (!fileUrl.value) return;
      // 在新窗口中打开图片
      window.open(fileUrl.value, '_blank');
    };

    /**
     * 查看订单详情
     */
    const viewOrder = (orderId: string) => {
      router.push(`/dashboard/order-detail/${orderId}`);
    };

    /**
     * 删除订单关联
     */
    const deleteOrderRelation = async (orderId: string) => {
      try {
        await deleteInvoiceOrderRelation(route.params.id as string, orderId);
        ElMessage.success('删除关联订单成功');
        // 重新获取关联订单
        fetchRelatedOrders(route.params.id as string);
      } catch (error) {
        console.error('删除关联订单失败:', error);
        ElMessage.error('删除关联订单失败');
      }
    };

    return {
      loading,
      invoice,
      columns,
      orderColumns,
      relatedOrders,
      isImage,
      isPdf,
      fileUrl,
      purchaserInfo,
      sellerInfo,
      totalAmount,
      totalTax,
      totalAmountWithTax,
      goBack,
      goToEdit,
      printInvoice,
      getCategoryText,
      formatAmount,
      formatDateTime,
      expandDetails,
      convertCurrency,
      previewVisible,
      showImagePreview,
      downloadImage,
      openInNewTab,
      viewOrder,
      deleteOrderRelation
    };
  }
});
</script>

<style scoped>
.invoice-detail {
  padding: 16px;
  background-color: #f0f2f5;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 16px;
  background-color: #fff;
  border-radius: 2px;
  padding: 16px;
}

.invoice-card {
  margin-bottom: 16px;
  background-color: #f9f9f9;
}

a-typography-title {
  margin-bottom: 20px;
  padding: 0 !important;
  background: transparent !important;
}

:deep(.ant-typography) {
  margin-bottom: 20px !important;
  padding: 0 !important;
  background: transparent !important;
  box-shadow: none !important;
}

.detail-item {
  margin-bottom: 12px;
  display: flex;
}

.detail-label {
  color: rgba(0, 0, 0, 0.65);
  margin-right: 8px;
  min-width: 80px;
}

.detail-value {
  color: rgba(0, 0, 0, 0.85);
  word-break: break-all;
}

.highlight-text {
  color: #f5222d;
  font-weight: bold;
}

.detail-table {
  margin-top: 16px;
  margin-bottom: 16px;
}

.table-footer {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  padding-right: 16px;
}

.total-row {
  margin-top: 8px;
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.total-amount {
  font-weight: bold;
  margin-left: 8px;
  min-width: 120px;
  text-align: right;
}

.highlight {
  color: #f5222d;
  font-size: 18px;
}

.file-preview {
  display: flex;
  justify-content: center;
  margin-top: 16px;
  position: relative;
}

.image-preview {
  position: relative;
  width: 100%;
  max-width: 800px;
  margin: 0 auto;
  cursor: pointer;
  overflow: hidden;
  transition: all 0.3s;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

.image-preview:hover::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.2);
  z-index: 1;
}

:deep(.ant-image) {
  display: block;
  width: 100%;
}

:deep(.ant-image-img) {
  width: 100%;
  object-fit: contain;
  max-height: 500px;
}

.image-toolbar {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 12px;
  background-color: rgba(0, 0, 0, 0.65);
  opacity: 0;
  transition: opacity 0.3s;
  z-index: 3;
}

.image-preview:hover .image-toolbar {
  opacity: 1;
}

:deep(.image-toolbar .ant-btn) {
  margin: 0 8px;
  background-color: rgba(255, 255, 255, 0.9);
  border-color: transparent;
}

:deep(.image-toolbar .ant-btn-primary) {
  background-color: #1890ff;
  color: white;
}

.pdf-preview,
.other-file {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
  padding: 16px;
  border: 1px dashed #d9d9d9;
  border-radius: 2px;
  background-color: #fafafa;
  cursor: pointer;
  transition: all 0.3s;
  position: relative;
}

.pdf-toolbar,
.file-toolbar {
  margin-top: 12px;
  display: flex;
  justify-content: center;
  gap: 12px;
}

.pdf-preview:hover,
.other-file:hover {
  border-color: #1890ff;
}

@media print {
  .page-header {
    display: none;
  }
}

.info-content p {
  margin: 8px 0;
  padding: 8px 16px;
  background-color: #f5f7fa;
  border-radius: 4px;
  white-space: pre-line;
  line-height: 1.6;
}

.empty-details {
  padding: 24px 0;
  background-color: #fafafa;
  border: 1px solid #f0f0f0;
  border-radius: 2px;
}

:deep(.ant-table-thead > tr > th) {
  background-color: #f5f7fa;
  font-weight: bold;
  text-align: center;
}

:deep(.ant-table-tbody > tr:hover > td) {
  background-color: #e6f7ff;
}

:deep(.ant-table-tbody > tr:nth-child(odd)) {
  background-color: #fafafa;
}

:deep(.ant-table-tbody > tr > td) {
  padding: 12px 8px;
  vertical-align: middle;
}

:deep(.ant-pagination) {
  margin: 16px 0;
}

.stat-card {
  background-color: #fff;
  border-radius: 2px;
  padding: 16px;
  text-align: center;
}

.stat-title {
  font-weight: bold;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  margin-top: 8px;
}

.detail-table-container {
  margin-bottom: 16px;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  background-color: #fff;
  border-radius: 2px;
}

.expand-btn {
  padding: 0;
}

.summary-container {
  margin-bottom: 16px;
}

.summary-card {
  background-color: #fff;
  border-radius: 2px;
  padding: 16px;
  text-align: center;
}

.summary-content {
  margin-bottom: 8px;
}

.summary-label {
  font-weight: bold;
}

.summary-value {
  font-size: 24px;
  font-weight: bold;
}

.highlight-money {
  color: #f5222d;
  font-weight: bold;
}
</style>